package com.cloud.controller;

import com.cloud.entity.Admin;
import com.cloud.service.AdminService;
import com.cloud.utils.GlobalConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 管理员模块
 *
 * @author .
 * created in 2020/1/11 11:17
 */

@Controller
@RequestMapping(value = "/admin")
public class AdminController {

    private Logger logger = LoggerFactory.getLogger(AdminController.class);

    private AdminService adminServiceImpl;

    public AdminController(AdminService adminServiceImpl) {
        this.adminServiceImpl = adminServiceImpl;
    }

    @GetMapping(value = "")
    public String toAdmin() {
        return "admin/login";
    }

    @GetMapping(value = "/emp")
    public String toEmp() {
        return "admin/emp";
    }

    @PostMapping(value = "/login")
    @ResponseBody
    public int login(HttpServletRequest request, @RequestParam("name") String name,
                     @RequestParam("password") String password) {
        HttpSession session = request.getSession();
        Admin admin = adminServiceImpl.findAdminByNameAndPwd(name, password);
        if (admin != null) {
            session.setAttribute("admin", admin);
            logger.info("【{}】登录成功，正在跳转中···", admin.getName());
            return GlobalConstant.SUCCESS;
        }
        return GlobalConstant.ERROR;
    }

    @GetMapping(value = "/isLogin")
    @ResponseBody
    public Admin isLogin(HttpServletRequest request) {
        HttpSession session = request.getSession();
        return (Admin) session.getAttribute("admin");
    }

    @GetMapping(value = "/logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("admin");
        session.invalidate();
        logger.info("管理员已退出登录");
        return "redirect:/admin";
    }

}
